package net.wzw.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author wzw
 * @date 2025/4/9
 * @Description 基于Redission分布式锁
 */
public class RedisLock {

    private RedissonClient redissonClient;

    public RedisLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /*
     * Description: redisson互斥锁,等待n秒自动失效
     * @param null
     * @Return: {@link null}
     * @Author: Administrator
     * @Date: 2025/4/9 11:52
     */
    public boolean lock(String key,int seconds){

          //先获取分布式锁
          RLock rLock = redissonClient.getLock(key);

          //如果已经加锁返回false
          if(rLock.isLocked()){

              return  false;
          }

          //加锁,如果在指定时间没释放锁,会自动在底层把锁释放掉
          rLock.lock(seconds, TimeUnit.SECONDS);
          //加锁成功返回true
          return true;
    }

    /*
     * Description: redisson互斥锁自动续期
     * @param null
     * @Return: {@link null}
     * @Author: Administrator
     * @Date: 2025/4/9 11:59
     */
     public boolean lock(String lock){

         //先获取分布式锁
         RLock rLock = redissonClient.getLock(lock);

         //如果已经获取锁了返回false
         if(rLock.isLocked()){

             return false;
         }

         //加锁
         rLock.lock();;
         //加锁成功,返沪true
         return  true;

     }

     /*
      * Description: 尝试加锁
      * @param null
      * @Return: {@link null}
      * @Author: Administrator
      * @Date: 2025/4/9 12:02
      */
     public boolean tryLock(String key,long timeout) throws InterruptedException{

         //获取锁
         RLock  rLock =  redissonClient.getLock(key);
         //尝试加锁
         return rLock.tryLock(timeout,TimeUnit.MILLISECONDS);

     }

     /*
      * Description: 手动释放锁
      * @param null
      * @Return: {@link null}
      * @Author: Administrator
      * @Date: 2025/4/9 12:04
      */
    public void unlock(String key){

        RLock rLock = redissonClient.getLock(key);

        //如果已锁定,则释放锁
        if(rLock.isLocked()){
            rLock.unlock();
        }

    }

   /**
    * 阻塞加锁
    * **/
   public boolean blockedLock(String key){

       //先获取分布式锁
       RLock rLock = redissonClient.getLock(key);
       //阻塞加锁,拿不到锁会一直等待
       rLock.lock();

       return true;

   }


}
